package work.linruchang.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.forte.util.Mock;
import com.forte.util.loader.MethodLoader;
import com.forte.util.mockbean.MockMapBean;

import java.util.HashMap;
import java.util.Map;

/**
 * @author LinRuChang
 * @version 1.0
 * @date 2022/10/08
 * @since 1.8
 **/
public class MyMockUtil {

    static {
        MethodLoader methodLoader = Mock.mockMethodLoader();
        methodLoader.append(ReflectUtil.getMethod(EnhanceMockUtil.class, "mockData", String.class, String.class));
        methodLoader.load();
    }


    public static Map<String,Object> mockResult(Map<String, Object> ruleMap) {
        MockMapBean test = Mock.setResult(UUID.fastUUID().toString(true), ruleMap, false);
        return test.getObject();
    }

    public static String mockResultJson(Map<String, Object> ruleMap) {
        return JSONUtil.toJsonStr(mockResult(ruleMap));
    }

    public static Map<String, Object> generateRuleMap(Map<String, Object> beanFieldStructure) {
        HashMap<String, Object> copyMap = MapUtil.newHashMap();
        BeanUtil.copyProperties(beanFieldStructure, copyMap);
        return generateRuleMapByLoop(copyMap);
    }

    /**
     * 基于结构生成mock规则
     *
     * @param beanFieldStructure Bean结构
     * @return
     */
    private static Map<String, Object> generateRuleMapByLoop(Map<String, Object> beanFieldStructure) {
        MapUtil.emptyIfNull(beanFieldStructure).forEach((properName, properType) -> {
            if(properType != null) {
                if(properType instanceof Class) {
                    beanFieldStructure.put(properName, StrUtil.format("@mockData('{}','{}')", ((Class<?>) properType).getName(), properName));
                }else {
                    generateRuleMapByLoop((Map<String, Object>) properType);
                }
            }else {
                beanFieldStructure.put(properName, StrUtil.format("@mockData('{}','{}')", null, properName));
            }
        });
        return beanFieldStructure;
    }




}
